<template>
  <div>
    <table>
      <thead>
        <tr>
          <th v-for="header in headers" :key="header">{{ header }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="node in nodes" :key="node.server_id">
          <td>{{ node.server_id }}</td>
          <td>{{ node.os_version }}</td>
          <td>{{ node.boot_time }}</td>
          <td>{{ node.cpu_available }}</td>
          <td>{{ node.memory_available_gb }}</td>
          <td>{{ node.running_tasks }}</td>
          <td>{{ node.worker_version }}</td>
          <td>
            <button @click="$emit('show-job', node.server_id)">Job详情</button>
            <label class="switch">
              <input type="checkbox" :checked="node.enabled" @change="toggleEnable(node.server_id, $event.target.checked)" />
              <span class="slider"></span>
            </label>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="pagination">分页: {{ pageId }}</div>
  </div>
</template>

<script>
import { getWorkerNodes, enableWorkerNode } from '../api';

export default {
  data() {
    return {
      headers: [
        '服务器编号', '操作系统版本', '开机时间', '可用cpu数量', '可用内存数量(GB)',
        '进行中的任务数量', 'worker node 版本', '操作',
      ],
      nodes: [],
      pageId: 1,
    };
  },
  created() {
    this.fetchNodes();
  },
  methods: {
    async fetchNodes() {
      const res = await getWorkerNodes({ page_id: this.pageId });
      this.nodes = res.data.map(node => ({ ...node, enabled: false })); // 默认禁用
    },
    async toggleEnable(workerId, isEnable) {
      await enableWorkerNode(workerId, isEnable ? 1 : 0);
      alert('成功，这个worker已经启用或者停用');
    },
  },
};
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
}
button {
  margin: 0 5px;
}
.pagination {
  margin-top: 10px;
  text-align: center;
}

/* 开关按钮样式 */
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: 0.4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: 0.4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:checked + .slider:before {
  transform: translateX(26px);
}
</style>
